<h1><?php echo $this->pageTitle; ?></h1>
<?php echo $ajax->form('DeRtH', 'post', array('update' => 'content', 'indicator' => 'indicator', 'url' => array('action' => 'save'))); ?>
<div class="toolbar">
    <div id="tLeft">
        <?php if ($mode == 'add') : ?>
            <?php echo $this->element('toolbar', array('buttons' => array('save', 'clear', 'back'))); ?>
        <?php else : // mode edit ?>
            <?php echo $this->element('toolbar', array('buttons' => array('add', array('print' => array('model' => 'DeRtH')), 'back'))); ?>
        <?php endif; ?>
    </div>
    <div id="tRight"><?php echo $this->element('neighbors', array('model' => 'DeRtH', 'title' => 'return_no')); ?></div>
</div>

<?php if ($mode == 'add' && $deRHs == null) :  // ถ้ายังไม่เคย Return ?>
    <script type="text/javascript">
        $j(function() {
            alert("There is no Delivery Request available to returned.");
            $j('.save').hide();
        });
    </script>

<?php endif; ?>

<?php echo $form->input('DeRtH.id'); ?>
<?php echo $form->hidden('mode', array('value' => $mode)); ?>

<fieldset>
    <table>
        <tr>
            <td width="150px"><?php echo $form->label('DeRtH.return_date', 'Return date'); ?></td>
            <td width="250px">
                <?php if ($mode == 'add') : ?>
                    <?php echo $html->tag('span', $today); ?>
                    <?php echo $form->hidden('DeRtH.return_date', array('id' => 'return_date', 'value' => $today)); ?>
                <?php else : ?>
                    <?php echo $html->tag('span', $this->data['DeRtH']['return_date']); ?>
                <?php endif; ?>
            </td>
            <td width="180px"><?php echo $form->label('DeRtH.delivery_request_head_id', 'Ref. by request no.', array('class' => 'required')); ?></td>
            <td>
                <?php if ($mode == 'add') : ?>
                    <?php echo $form->hidden('DeRtH.delivery_request_head_id', array('id' => 'hidDeRtHDeRHId')); ?>
                    <div id="divDeRH">
                        <?php echo $form->select('DeRtH.delivery_request_head_id', $deRHs, null); ?>
                    </div>
                    <span id="spanDeRH"></span>
                <?php else : ?>
                    <?php echo $html->tag('span', $this->data['DeRH']['request_no']); ?>
                <?php endif; ?>
            </td>
        </tr>
        <tr>
            <td><?php echo $form->label('DeRtH.return_no', 'Return no'); ?></td>
            <td>
                <?php if ($mode == 'add') : ?>
                <?php else : ?>
                    <?php echo $html->tag('span', $this->data['DeRtH']['return_no']); ?>
                <?php endif; ?>
            </td>
            <td><?php echo $form->label('DeRtH.supplier_id', 'Vendor'); ?></td>
            <td>
                <?php if ($mode == 'add') : ?>
                    <?php echo $form->hidden('DeRtH.supplier_id'); ?>
                    <span id="DeRtHVendor"></span>
                <?php else : ?>
                    <?php echo $this->data['Supplier']['name']; ?>
                <?php endif; ?>
            </td>
        </tr>
        <tr>
            <td><?php echo $form->label('DeRtH.return_by', 'Return by'); ?></td>
            <td colspan="3">
                <?php if ($mode == 'add') : ?>
                    <?php echo $html->tag('span', $return_by); ?>
                    <?php echo $form->hidden('DeRtH.return_by', array('value' => $return_by)); ?>
                <?php else : ?>
                    <?php echo $html->tag('span', $this->data['DeRtH']['return_by']); ?>
                <?php endif; ?>
            </td>
        </tr>
    </table>
</fieldset>

<fieldset>
    <table class="data">
        <thead>
            <tr>
                <th width="35px">No</th>
                <th width="130px">Part no.</th>
                <th width="120px">Stock code</th>
                <th>Description</th>
                <th width="100px">Return Qty</th>
                <th width="50px">Unit</th>
                <th width="60px">Price</th>
                <th width="60px">Amount</th>
                <?php if ($mode == 'add') : ?>
                    <th class="action">&nbsp;</th>
                <?php endif; ?>
            </tr>
        </thead>
        <tbody id="productRow">
            <?php if ($mode == 'edit') :
                $total = 0;
             $count = count($this->data['DeRt']);
                for ($i = 0; $i < $count; ++$i) : ?>
                    <tr class="<?php echo (($i + 1) % 2 == 0) ? 'even-cell' : 'odd-cell'; ?>">
                        <td><span><?php echo $i + 1; ?></span></td>
                        <td>
                            <?php
                            echo $html->link($this->data['DeRt'][$i]['Product']['supplier_part_no'], '/supplier_inventories/view/' . $this->data['DeRt'][$i]['cust_product_site_id'] . '/' . strtotime('now'), array('target' => '_blank'));
                            ?>
                        </td>
                        <td class="center"><?php echo $this->data['DeRt'][$i]['CustProductSite']['stock_code']; ?></td>
                        <td>
                            <?php
                            echo!empty($this->data['DeRt'][$i]['CustProductSite']['text']) ?
                                    $this->data['DeRt'][$i]['CustProductSite']['text'] :
                                    $this->data['DeRt'][$i]['Product']['text'];
                            ?>
                        </td>
                        <td class="text-right"><?php echo $this->data['DeRt'][$i]['return_qty']; ?></td>
                        <td class="center">
                            <?php echo $this->data['DeRt'][$i]['Product']['Unit']['title']; ?>
                        </td>
                        <td class="text-right">
                            <span id="spanDeR<?php echo $i; ?>Price"><?php echo number_format($this->data['DeRt'][$i]['price'], 2); ?></span>
                        </td>
                        <td class="text-right">
                            <?php
                            $amount = $this->data['DeRt'][$i]['return_qty'] * $this->data['DeRt'][$i]['price'];
                            $total += $amount;
                            echo $html->tag('span', number_format($amount, 2), array('id' => "DeR{$i}Amount"));
                            ?>
                        </td>
                    </tr>
                <?php endfor; ?>
            <?php endif; ?>
        </tbody>
        <tfoot id="tableFooter">
            <tr>
                <td class="text-right" colspan="7">Total</td>
                <td class="text-right">
                    <span id="spanTotal">
                        <?php echo $mode != 'add' ? number_format($total, 2) : ''; ?>
                    </span>
                </td>
                <?php if ($mode == 'add') : ?>
                    <td>&nbsp;</td>
                <?php endif; ?>
            </tr>
        </tfoot>
    </table>
</fieldset>
<fieldset>
    <table>
        <tr>
            <td width="50px" class="top"><?php echo $form->label('DeRtH.remark'); ?></td>
            <td>
                <?php
                if ($mode == 'add') {
                    echo $form->textarea('DeRtH.remark', array('cols' => 80, 'rows' => 3));
                } else {
                    echo empty($this->data['DeRtH']['remark'])? '-': $this->data['DeRtH']['remark'];
                }
                ?>
            </td>
        </tr>
    </table>
</fieldset>
<?php echo $form->end(); ?>
<?php if ($mode == 'add') : ?>
    <script type="text/javascript">
        // JSON เก็บ part no ที่ป้อนเข้ามา อ้างไปยังลำดับแถว
        var partNos = {};

        requestDeR = function(event) {
            var element = Event.element(event);
            var part_no = $j.trim($F(element));
            var no = element.readAttribute("no");   // ลำดับแถวปัจจุบัน เริ่มที่ 0
            if(part_no == "") {return;}

            // ถ้ายังไม่มี part no นี้อยู่
            if (partNos[part_no] == null) {
                var id = $j("#DeRtHDeliveryRequestHeadId").val();

                if (id == "") {
                    alert("Please select a Return no.");
                    $j('#DeRt' + no + 'PartNo').val('');
                    return;
                }

                var url = base + "/delivery_returns/json_find_by_part_no_delivery_request_head_id/";
                var params = {part_no: part_no, delivery_request_head_id: id};
                postRequest(url, params, function(data) {
                    // ไม่พบข้อมูล (กรอกข้อมูลผิด...)
                    if (data == false) {
                        element.clear();
                        alert("No product found.");
                        return;
                    }

                    $j("#DeRt" + no + "PartNo").hide();
                    $j("#DeRt" + no + "PartNoSpan").text(data.Product.supplier_part_no).show();
                    $j("#DeRt" + no + "StockCode").text(data.CustProductSite.stock_code);
                    $j("#DeRt" + no + "CustProductSiteId").val(data.DeR.cust_product_site_id);
                    $j("#DeRt" + no + "DeliveryRequestId").val(data.DeR.id);
                    $j("#DeRt" + no + "ProductText").text(data.CustProductSite.text != null? data.CustProductSite.text: data.Product.text);
                    $j("#DeRt" + no + "ProductId").val(data.DeR.product_id);
                    $j("#DeRt" + no + "RequestQty").text("/" + data.DeR.receive_qty);
                    $j("#DeRt" + no + "ProductUnitTitle").text(data.Product.Unit.title);
                    $j("#DeRt" + no + "ReturnQty").val(0);
                    $j("#DeRt" + no + "PriceUnit").text(data.DeR.price);
                    $j("#DeRt" + no + "Price").val(data.DeR.price);
                    checkReturnQty(no);

                    // ดักจับ Event กดลบแถว.
                    $j('#linkDeRt' + no + 'Delete').bind('click', function() {
                        // ลบรายการ part no ออกจาก list
                        var p = $j("#DeRt" + no + "PartNoSpan").text();
                        var sc = $j("#DeRt" + no + "StockCode").text();
                        partNos[p] = undefined;
                        partNos[sc] = undefined;

                        // ลบ แถว
                        $j(this).parents('tr').remove();

                        // จัดลำดับตัวเลขหน้าแถวใหม่
                        $j('#productRow').runno();
                    }).show();

                    // บันทึกแถวปัจจุบันของ part no
                    partNos[data.Product.part_no] = no;
                    partNos[data.Product.supplier_part_no] = no;
                    partNos[data.CustProductSite.stock_code] = no;
                    var nextRow = (parseInt(no) + 1);
                    createRow(nextRow)
                    $("DeRt" + nextRow + "PartNo").focus();
                });
            } else {
                element.clear();
                var row = partNos[part_no]; // แถวที่มี part_no นี้อยู่
                $("DeRt" + row + "ReturnQty").value = parseInt($("DeRt" + row + "ReturnQty").value) + 1;
                setTimeout(function() {
                    $("DeRt" + no + "PartNo").focus();
                }, 100);
                checkReturnQty(row);
            }
        }

        checkReturnQty = function(no) {
            var receiveQty = parseInt($j("#DeRt" + no + "RequestQty").text().substring(1)) // innerHTML = "/[RequestQty]"
            var returnQty = parseInt($F("DeRt" + no + "ReturnQty"))
            if (returnQty > receiveQty) {
                alert("Please return quantity less than return quantity")
                $j("#DeRt" + no + "ReturnQty").val(receiveQty);
                returnQty = receiveQty;
            }

            var price = parseFloat($j("#DeRt" + no + "ReturnQty").parents('tr').find(':input[id$=Price]').val().replace(',', ''));
            var amount = returnQty * price;
            $j("#DeRt" + no + "ReturnQty").parents('tr').find('[id$=Amount]').text(amount.toFixed(2));

            // cal total
            var total = 0;
            $j('span[id$=Amount]').each(function() {
                var amount = parseFloat($j.trim($j(this).text()).replace(',', ''));
                if (!isNaN(amount)) {
                    total += amount;
                }
            });
            $j('#spanTotal').text(total.toFixed(2));
        }

        function createRow(row) {
            var tBody = $("productRow");
            var tr = new Element("tr");
            tr.addClassName(((row + 1) % 2 == 0)? "even-cell" : "odd-cell");

            tr.update('<input id="DeRt' + row + 'Id" type="hidden" value="" name="data[DeRt][' + row + '][id]" />');

            var tdNo = new Element("td");
            tdNo.update('&nbsp;');
            tr.insert(tdNo);

            var tdPartNo = new Element("td");
            tdPartNo.insert('<input id="DeRt' + row + 'PartNo" type="text" value="" no="' + row + '" name="data[DeRt][' + row + '][part_no]"/>');
            tdPartNo.insert('<input id="DeRt' + row + 'ProductId" type="hidden" value="" name="data[DeRt][' + row + '][product_id]"/>');
            tdPartNo.insert('<input id="DeRt' + row + 'DeliveryRequestId" type="hidden" value="" name="data[DeRt][' + row + '][delivery_request_id]"/>');
            tdPartNo.insert('<input id="DeRt' + row + 'CustProductSiteId" type="hidden" value="" name="data[DeRt][' + row + '][cust_product_site_id]"/>');
            tdPartNo.insert('<span id="DeRt' + row + 'PartNoSpan" style="display: none"></span>');
            tr.insert(tdPartNo);

            var tdStockCode = new Element("td", {'class': 'center'});
            tdStockCode.insert('<span id="DeRt' + row + 'StockCode"></span>');
            tr.insert(tdStockCode);

            var tdTitle = new Element("td");
            tdTitle.insert('<span id="DeRt' + row + 'ProductText"></span>');
            tr.insert(tdTitle);

            var tdReturnQty = new Element("td");
            var div = new Element("div", {'class': 'inline'});
            div.update('<input id="DeRt' + row + 'ReturnQty" no="' + row + '" class="text-right" type="text" value="" maxlength="3" size="3" name="data[DeRt][' + row + '][return_qty]"/>');
            tdReturnQty.insert(div);
            tdReturnQty.insert('<span id="DeRt' + row + 'RequestQty"></span>');
            tr.insert(tdReturnQty);

            var tdUnit = new Element("td", {'class': 'center'});
            tdUnit.insert('<span id="DeRt' + row + 'ProductUnitTitle"></span>');
            tr.insert(tdUnit);

            var tdPriceUnit = new Element("td", {'class': 'text-right'});
            tdPriceUnit.insert('<span id="DeRt' + row + 'PriceUnit"></span>');
            tdPriceUnit.insert('<input id="DeRt' + row + 'Price" type="hidden" value="" name="data[DeRt][' + row + '][price]"/>');
            tr.insert(tdPriceUnit);

            var tdAmount = new Element("td", {'class': 'text-right'});
            tdAmount.insert('<span id="DeRt' + row + 'Amount"></span>');
            tr.insert(tdAmount);

            var tdDelete = new Element("td", {"class": "center"});
            tdDelete.insert('<a href="#" id="linkDeRt' + row + 'Delete" style="display: none;"><?php echo $html->image('icon/delete.png', array('title' => 'Delete', 'alt' => 'Delete')); ?></a>');
            tr.insert(tdDelete);

            tBody.insert(tr);
            $j('#productRow').runno();
            addRowListener(row);
        }

        function addRowListener(row) {
            $("DeRt" + row + "PartNo").observe('keypress', partNoKeyPress);

            $("DeRt" + row + "PartNo").observe('blur', function(event) {
                requestDeR(event);
            });

            $("DeRt" + row + "ReturnQty").observe('keypress', stopKeyEnter);
            $("DeRt" + row + "ReturnQty").observe('change', function(event) {
                checkReturnQty(Event.element(event).readAttribute("no"));
            });

        }

        /**
         * จัดการการเลือก Return no โดยการกดปุ่ม search
         */
        deliveryHandler = function(id) {
            if (id != '') {
                requestJSON("delivery_returns", id, function(data) {
                    $j("#divDeRH").hide();
                    $j("#spanDeRH").text(data.DeRH.request_no);
                    $j("#DeRtHDeRHId").val(data.DeRH.id);
                    $j("#hidDeRtHDeRHId").val(data.DeRH.id);

                    $j("#DeRtHVendor").text(data.Supplier.name);
                    $j("#DeRtHSupplierId").val(data.Supplier.id);
                    $j("#DeRtHVendor").show();
                });
            }
        };

        $j(function() {
            createRow(0);
            $j("#DeRtHDeliveryRequestHeadId").bind("change", function() {
                deliveryHandler($j(this).val());
            });

            $j('#DeRtHId').parent('form').beforeSubmit(function() {
                if ($j.areEmpty('DeRtHDeliveryRequestHeadId')) {
                    return false;
                }

                if (!$j.validateColumns('ReturnQty', 'Return Qty', {callback: $j.QTY})) {
                    return false;
                }
                return true;
            });
        })
    </script>
<?php endif; ?>